(function($, SH) {
	
	
	
	//splittext function is used to split the continous string
	function splitText(str){
		if(str.indexOf(" ")!=-1 || str.length <15)
			return str;
		var arr = new Array();
		arr = str.split("");
		var finalStr = "";

		for(var i=0;i<arr.length;i++){
			if(i>0 && (i+1)%15 == 0)
				finalStr += arr[i] + "<br />";
			else
				finalStr += arr[i];
		}
		return finalStr;
	}

	//get omniture cookie info to flex
	function getCookieAllIn(name) {
		var nameEQ = name+'=';
		if (!document.cookie) {
			return false;
		}
		var ca = document.cookie.split(';');
		for(var i=0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return false;
	}

	function toggleCookie(elem, cookielet) {
		var val = 0;

		if($(elem).parents("div.p-wrapper").hasClass("p-collapse")){
			val = 1;
		}
		$.writeCookielet("STUB_BROWSE_INFO",cookielet,val, 1080);
	}
	function checkCookie(){

		var mz = $.readCookielet("STUB_PERSISTENT","mz");
		var smz = $.readCookielet("STUB_SESSION","smz");
		mz = mz.substring(0,1);
		smz = smz.substring(0,1);
		
		storedU2 = $.readCookielet("STUB_SECR","u2");
		storedGen3 = $.readCookielet("STUB_SECR","gen3_access");
		u2_Guid = $.trim(storedU2.substr(0, storedU2.indexOf("~^~")));
		gen3_userToken = $.trim(storedGen3.substr(0, storedGen3.indexOf("~^~")));
//		console.log("++++ in checkCookie ++++ storedU2: " + u2_Guid);
//		console.log("SH.wishlistAdded: " + SH.wishlistAdded);
		
		if (StubHub.hideOverLay == true){
			$('#seatMapOverlay').addClass("p-offscreenOnLoad");
		}
		else if (mz != 1 && googleMapLoaded == true && smz == '') {
			$('#seatMapOverlay').removeClass("p-offscreenOnLoad");
			$('#mapZoomInfo').removeAttr('checked');
		}
	}

	function updateWidgets() {

		if(typeof(bNoBrowseHistory) != "undefined" && bNoBrowseHistory ){
			$("#viewHistory .p-widget h2 a").click();
		}
		var ue = $.readCookielet("STUB_BROWSE_INFO","ue");
		var sf = $.readCookielet("STUB_BROWSE_INFO","sf");
		var z = $.readCookielet("STUB_BROWSE_INFO","z");

		if(ue == 0 && !$("#upcomingEvents .p-wrapper").hasClass("p-collapse")) {
			$("#upcomingEvents .p-widget h2 a").click();
		}
		if(ue != "0" && ue != "1"){
			$("#upcomingEvents .p-widget h2 a").click();
		}

		if(typeof(upcomingEvent) != "undefined" && upcomingEvent == "false"){
			$("#upcomingEvents").addClass("hideOnLoad");
		}
		// for ticket features
		if(sf == "1"){
			$("#select_features .p-widget h2 a").click();
		}

		//zone
		if(z == "1"){
			$("#select_zone .p-widget h2 a").click();
		}


	}


	/* ============== Compare popup ===============*/


	//;(function($){
	var qty = ""; //based on condition value will change
	var isTicketFeatureRow = false;
	var emptyTD = '<td rowspan="10" class="empty leftborder">&#160;</td>';
	var deliveryStr = "&#160;";
	var listingAttributeList = new Array();
	var actualRow = 0;
	var listingId = 0;
	var isRemoveOn = false;
	var comparableTickets = new Array();
	var listingAttribute  = new Array();
	compareData={};
	ticketAttributeList=null;

	var listAttributeDescription = new Array();
	var buyQuantity = "";
	var checkoutQuantity = "";
	var metaPack = SH.metaPack || {};

	function openCheckout(id){
		if(buyQuantity > 9)
			window.location = document.location.href+"?c=1&ticket_id="+id+"&quantity="+checkoutQuantity;
		else
			window.location = document.location.href+"?c=1&ticket_id="+id+"&quantity="+buyQuantity;

		$(".ui-dialog-titlebar-close").trigger("click");
	}

	function removeCompareItem(listingObj){
		if(!isRemoveOn){
			isRemoveOn = true;
			listingId = listingObj.id;

			$('#td0'+listingId).html("&#160;&#160;&#160;&#160;&#160;").removeClass("features2").addClass("remove");
			$('#td1'+listingId).html("&#160;").removeClass("features1").addClass("remove");
			$('#td2'+listingId).html("&#160;").removeClass("features2").addClass("remove");
			$('#td3'+listingId).html("&#160;").removeClass("features1").addClass("remove").html('<nobr>&#160;&#160;&#160;<img src="'+staticUrl+'/resources/mojito/img/pattern/phoenix/throbber_24.gif" class="textmiddle"/> '+ ComparePopup.removing  +'</nobr>');
			$('#td4'+listingId).html("&#160;").removeClass("features2").addClass("remove");
			$('#td5'+listingId).html("&#160;").removeClass("features1").addClass("remove");
			$('#td6'+listingId).html("&#160;").removeClass("features2").addClass("remove");
			$('#td7'+listingId).html("&#160;").removeClass("features2").addClass("remove");
            $('#td73'+listingId).html("&#160;").removeClass("features2").addClass("remove");
			$('#td9'+listingId).html("&#160;").removeClass("features1").addClass("remove");
			$('#td10'+listingId).html("&#160;").removeClass("features2").addClass("remove");

			//totCol--;
			actualRow = actualRow - 1;

			//window.setTimeout(removeRow, 500, listingId);
			var current_timer_remRow = window.setTimeout(function () {
		                removeRow();
		           }, 1500);

			//add empty column at the end
			//window.setTimeout(appendEmptyRow, 1500, emptyTD);
			var current_timer_emptyRow = window.setTimeout(function () {
		                appendEmptyRow(1);
		            }, 1540);
		}
	}

	function appendEmptyRow(num){
		//ADD EMPTY ROW IN CASE LISTING LESS THAN 5 ITEMS
		for(var j=0;j<num;j++){
			$('#compareTicket .compareTable tr:first').append(emptyTD);
		}
		isRemoveOn = false;
	}

	function removeRow(){

		$('#td0'+listingId).remove();
		$('#td1'+listingId).remove();
		$('#td2'+listingId).remove();
		$('#td3'+listingId).remove();
		$('#td4'+listingId).remove();
		$('#td5'+listingId).remove();
		$('#td6'+listingId).remove();
		$('#td7'+listingId).remove();
 	    $('#td73'+listingId).remove();
		$('#td9'+listingId).remove();
		$('#td10'+listingId).remove();

		if(actualRow<=2)
			hideRemoveLink();

	}

	function hideRemoveLink(){
		$('.pipe').css("visibility","hidden");
		$('.remLink').css("visibility","hidden");
	}
	function renderListing(){

		var td11 = '<td> '+ComparePopup.price+' <br/> <span class="notes"> '+ComparePopup.perTicket+' </span></td>';
		var td21 = '<td> '+ComparePopup.zoneSection+' </td>';
		var td31 = '<td> '+ComparePopup.row+' </td>';
		var td41 = '<td> '+ComparePopup.seat+' </td>';
		var td51 = '<td> '+ComparePopup.quantity+' <br/> '+ComparePopup.available+' </td>';
		var td61 = '<td> '+ComparePopup.delivery+' <br/> '+ComparePopup.method+' </td>';
		var td71 = '<td> '+ComparePopup.ticket+' <br/> '+ComparePopup.features+' </td>';
        var td73 = '<td> '+ComparePopup.faceValue+' <br/> <span class="notes">' + ComparePopup.perTicket + ' </span></td>';
		var td81 = '<td>&#160;</td>';
		var td91 = '<td>'+ComparePopup.delivery+' <br/> '+ComparePopup.date+'</td>';
		if(SH.eventBundledType == 2){
		}else if(SH.eventBundledType == 4){
		}else{
			var td101 = '<td>'+ComparePopup.delivery+' <br/> '+ComparePopup.fee+'</td>';
		}
		var marginleft = "";
		if($.browser.msie){
			marginleft = "";
		}

		var button = "";
		var ticketFeature = "&#160;";
		var len=listingAttribute.length;
		var compticketsLen = comparableTickets.length;
		var re = new RegExp(",","g");
		var compareObj = "";
		var qtyForUrl = 0;
		var attributeId = 0;
		var attributeDesc = "";

		for(var i=0;i<compticketsLen;i++){
			compareObj = comparableTickets[i];
			qty = compareObj.quantity;
			qtyForUrl = qty;

           if(compticketsLen ==2) {
			  button = '<div class="noResize"><button style="margin-top:3px; margin-left:25px;" class="btn-sprite-buy btn-sprite btn-sprite-medium btn-sprite-medium-white" id="buy'+i+'" href="?ticket_id='+ compareObj.listingId +'&quantity=' + qtyForUrl +'" txtId="'+compareObj.listingId+'"><span class="btn-sprite-text">' + StubHub.btnBuy + '</span></button></div>';
           } else {
			  button = '<div class="noResize"><div style="float:left;margin-top:-8px"><button class="btn-sprite-buy btn-sprite btn-sprite-medium btn-sprite-medium-white" id="buy'+i+'" href="?ticket_id='+ compareObj.listingId +'&quantity=' + qtyForUrl +'" txtId="'+compareObj.listingId+'"><span class="btn-sprite-text">' + StubHub.btnBuy + '</span></button></div><label class="pipe">|</label><a href="javascript:void(0);" id="'+i+'" class="remLink" name="'+ compareObj.listingId +'">'+ComparePopup.remove+' </a></div>';
           }

            // to keep currenty US style rather than using new one.
            if (typeof shMultiCurrency === 'object') {
               td11 += '<td class="leftborder" id="td0' + i + '"> '+ shMultiCurrency.renderPriceRaw(compareObj.currentPrice, compareObj.currencyCode, "long") + '</td>';
            } else {
               td11 += '<td class="leftborder" id="td0' + i + '"> '+ compareObj.currentPrice + ' ' + compareObj.currencyCode + '</td>';
            }

			var section = splitText(compareObj.venueConfigSectionAlias);
			td21 += '<td class="leftborder" id="td1' + i + '"> '+ section +' </td>';
			row = compareObj.rowDesc;

			if(typeof(row) != "undefined"){
				if(row.indexOf(",")!= -1)
					row += " (piggyback)";
				row = row.replace(re,", ");
			}

			td31 += '<td class="leftborder" id="td2' + i + '"> '+row+' </td>';

			if(compareObj.seats != null && compareObj.seats != 'null')
				row = compareObj.seats.replace(re,", ");
			else{
				row = ComparePopup.notAppl;
			}
			td41 += '<td class="leftborder" id="td3' + i + '"> '+row+' </td>';

			if(compareObj.split == 'true'){
				td51 += '<td class="leftborder" id="td4' + i + '"> '+ComparePopup.upto+' '+ qty+ ' </td>';
			} else {
				td51 += '<td class="leftborder" id="td4' + i + '"> '+qty+ ' </td>';
			}

			/*if(compareObj.isCharity){
				ticketFeature += '<span class="charity">&#160;</span>';
			}
			if(compareObj.isExclusiveOffer){
				ticketFeature += '<span class="exclusive">&#160;</span>';
			}
			if(compareObj.isExcludeObstructed){
				ticketFeature += '<span class="obstructed">&#160;</span>';
			}
			if(compareObj.isWheelChair){
				ticketFeature += '<span class="wheelchair">&#160;</span>';
			}
			if(compareObj.isAlcholFree){
				ticketFeature += '<span class="alcoholFree">&#160;</span>';
			}
			if(compareObj.isParkingPassIncluded){
				ticketFeature += '<span class="parking">&#160;</span>';
			}
			if(compareObj.isPiggyback){
				ticketFeature += '<span class="piggyback">&#160;</span>';
			}
			if(compareObj.isAisle){
				ticketFeature += '<span class="aisle">&#160;</span>';
			}


			ticketFeature += '<br/>'; */
			td61 += '<td class="leftborder"  id="td5' + i + '"> <div id="delivery'+compareObj.listingId+'">'+ComparePopup.curNotAvail+'</div> </td>';
			td91 += '<td class="leftborder"  id="td9' + i + '"> <div id="date'+compareObj.listingId+'">'+ComparePopup.curNotAvail+'</div> </td>';
			if(SH.eventBundledType == 2){

			}else if(SH.eventBundledType == 4){

			}else{
				td101 += '<td class="leftborder"  id="td10' + i + '"> <div id="fee'+compareObj.listingId+'">'+ComparePopup.curNotAvail+'</div> </td>';
			}

			list = compareData["l" + compareObj.listingId];

			if(list){
				var listObj = list;
				if(listObj.length >0){

					if(listObj.length ==1){ //no bullet
						ticketFeature += "<ul class='singlefeature' style='"+marginleft+"'>";
					}
					else{
						ticketFeature += "<ul style='"+marginleft+"'>";
					}
					for(var j=0;j<listObj.length;j++){
					   attributeId = listObj[j];

					   for(var k=0;k<ticketAttributeList.length;k++){

						   var attr = ticketAttributeList[k];
						   if (attr.id == attributeId){

							   attributeDesc =   attr.description;
							   break;
						   }
					   }

					   ticketFeature += "<li>"+attributeDesc +"</li>";
					   /*if(attributeDesc != "Parking Pass" && attributeDesc != "Wheelchair seating"){
						   ticketFeature += "<li>"+attributeDesc +"</li>";
					   }*/
					}
					ticketFeature += "</ul>";
				}
			}

			if(ticketFeature.length > 11){
				isTicketFeatureRow = true;
			}
			td71 += '<td  class="leftborder" id="td6' + i + '"> '+ ticketFeature +' </td>';
            td73 += '<td  class="leftborder" id="td73' + i + '"> '+ compareObj.faceValue +' </td>';
			td81 += '<td class="leftborder padd" id="td7' + i + '">'+button+'</td>';
			deliveryStr="";
			button ="";
			ticketFeature="&#160;";
			row = "";
			compareObj = "";
			attributeId = "";
			attributeDesc = "";
		}

		actualRow = i; // hold the number of td containing data

		//append empty row, if any required
		if(actualRow<5){
			for(var j=actualRow;j<5;j++){
				td51 += emptyTD;
			}
		}

		//append td to tr
		td11 = '<tr>'+td11+'</tr>';
		td21 = '<tr>'+td21+'</tr>';
		td31 = '<tr>'+td31+'</tr>';
		td41 = '<tr>'+td41+'</tr>';
		td51 = '<tr>'+td51+'</tr>';
		td61 = '<tr>'+td61+'</tr>';
        td73 = '<tr>'+td73+'</tr>';
		td81 = '<tr>'+td81+'</tr>';
		td91 = '<tr id="tr91">'+td91+'</tr>';

        // Do not display face value
        if (SH.ticketListRawResponse && !SH.ticketListRawResponse.isShowFaceValue) {
           td73 = '';
        }

		if(SH.eventBundledType == 2){

		}else if(SH.eventBundledType == 4){

		}else{
			td101 = '<tr id="tr101">'+td101+'</tr>';
		}

		if(isTicketFeatureRow)
			td71 = '<tr>'+td71+'</tr>';
		else
			td71 = '';

        var strHTML = '';
        if (SH.eventBundledType == 2) {
		   strHTML = '<table class="compareTable" cellspacing="0">'+td51+td21+td31+td41+td71+td61+td91+td11+td73+td81+'</table>';
		} else if (SH.eventBundledType == 4) {
           strHTML = '<table class="compareTable" cellspacing="0">'+td51+td21+td31+td41+td71+td61+td91+td11+td73+td81+'</table>';
		} else {
           strHTML = '<table class="compareTable" cellspacing="0">'+td51+td21+td31+td41+td71+td61+td91+td101+td11+td73+td81+'</table>';
		}
		//add delivery date
		var url = "/feedservices/lcsServices/listingIds/";
		var ajaxListing =new Array();
		for(var i=0;i<comparableTickets.length;i++){
			url+=comparableTickets[i].listingId;
			if(i!=comparableTickets.length-1){
				url+=",";
			}
		}

		url += "/userGuid/"+userGuid;
		$.ajax({
			url: url,
			contentType:"application/json",
			success: function (data)
			{
				var listing = data.EventTicketExpectedDeliveryDates.EventTicketExpectedDeliveryDate;

				if(!listing){
					$("#tr91, #tr101").addClass("hideOnLoad");
				}
				for(index in listing){
					listingId = listing[index].ListingId;
					expectedDeliveryDate = listing[index].ExpectedDeliveryDate;
					deliveryMethodType = listing[index].DeliveryMethodType;
					deliveryMethodDesc = listing[index].DeliveryMethodDesc;
					expectedDeliveryDateDesc = listing[index].ExpectedDeliveryDateDesc;
					deliveryFee = listing[index].DeliveryFee;
					dateStr = expectedDeliveryDateDesc + "<br/><b>"+expectedDeliveryDate+"</b>";
					deliveryStr = (deliveryMethodType=="ElectronicInstantDownload") ? deliveryMethodDesc + " - <br/><label>"+ComparePopup.instantDownload+"</label>" :  deliveryMethodDesc;
					feeStr = (deliveryMethodType=="FedEx") ? deliveryFee + "<br/>" +ComparePopup.feesVary : deliveryFee;
					$("#date"+listingId).html(dateStr);
					
					if(metaPack.isEnabled){
						$.each(comparableTickets, function(i, obj){
							if(obj.listingId == listingId && obj.deliveryMethod == metaPack.description){
								deliveryStr = metaPack.description;
								return false;
							}
						});
					}
					
					$("#delivery"+listingId).html(deliveryStr);
					if(SH.eventBundledType == 2){
					}else if(SH.eventBundledType == 4){
					}else{
						$("#fee"+listingId).html(feeStr);
					}
				}
			}
		});

		return strHTML;
	}
	/* ======+====== Bindings ======+====== */
	$(function() {
		
        // adding wishlist functions
  		 var showWLTooltip = function(sourceContent) {
  			   $('#wishlistbutton').overlay({
  			       trigger: "mouseover",
  			       width: 300,
  			       style: "callout",
  			       preferedPosition: "below",
  			       align: "center",
  			       preferedAlignment: "relative",
  			       exclusive: true,
  			       overlayClass: "ov-bubble",
  			       openDelay: 100,
  			       closeDelay: 100,
  			       showCloseIcon: false,
  			       modal: false,
  			       offsetX: 0,
  			       offsetY: 0,
  			       source: '#' + sourceContent,
  			       open:function(){
  			       		
  			       }

  			   });
  		 };

  		wishlistError = function() {
  			   //console.log("Initial wishlist check Error occurs");
  		};

  		wishlistSuccessGet = function(resp) {

  			   //console.log("json respond: " + resp.wishlist.entityList.length);
  			   for(i = 0; i < resp.wishlist.entityList.length; i++ ) {
  					var eventId = resp.wishlist.entityList[i].id;
  					var totalWishlist = resp.wishlist.entityList.length;
  					//console.log("evebt["+i+"]", eventId + " == " + StubHub.eventID );
  					if(eventId == StubHub.eventID){
//  						console.log("found match" + " need to set SH.wishlistAdded to " + SH.wishlistAdded);
  						showAfterWishlistIsAdded();
  					} else {
  						showWLTooltip('wishlistNotAdded');
  					}
  			   }

  		       if(gup('action') == 'addtowishlist' && SH.wishlistAdded == false)
  				{
  					 //console.log("found action=addtowishlist" + " SH.wishlistAdded:" + SH.wishlistAdded);
  					 wishListAjaxAdd('POST', wishlistAjaxBeforeSendPost, wishlistSuccessPost, wishlistError);
  				 }




  		};

  		appDomain = function(){
  			return (window.location.host).split('.')[1];
  		}

  		showAfterWishlistIsAdded = function(){
  			SH.wishlistAdded = true;
  			$('#wishlistbutton span').html(onYourWishlist);
  			$('#wishlistbutton').addClass('disableLink');
  			showWLTooltip('wishlistAdded');
  		}

  		wishlistSuccessPost = function(resp) {
  			//console.log("Wishlist added successfully");
  			showAfterWishlistIsAdded();
  			$("<div class='wishlistConfirmationMessage'>You just added this event to your <a href='/wishlist/'>wishlist</a></div>").insertBefore($('#eventsummary'));
  		};


  		wishlistAjaxBeforeSendGet = function(xhr) {
  			xhr.setRequestHeader("TARGET_HOST", appDomain());
  			xhr.setRequestHeader("Authorization", "Bearer " + gen3_userToken);
  		};

  		wishlistAjaxBeforeSendPost = function(xhr) {
  		     xhr.setRequestHeader("Accept", "application/json");
  		     xhr.setRequestHeader("Content-Type", "application/json");
  		     xhr.setRequestHeader("Target_host", appDomain());
  		     xhr.setRequestHeader("Authorization", "Bearer " + gen3_userToken);
  		};


  		wishlistAPI = function(guid){
  			return "/shape/user/customers/v1/" + guid + "/wishlists/0";
  		};

  		wishListAjax = function(type, wishlistAjaxBeforeSendGet, wishlistSuccessGet, wishlistError){
  			$.ajax({
  				   url: wishlistAPI(u2_Guid),
  				   type: type,
  				   dataType: 'json',
  				   beforeSend: wishlistAjaxBeforeSendGet,
  				   cache: false,
  				   success: wishlistSuccessGet,
  				   error: wishlistError
  				 });
  		};

  		wishListAjaxAdd = function(type,wishlistAjaxBeforeSendPost, wishlistSuccessPost, wishlistError){
  			if (typeof(StubHub.eventID) == 'undefined' ){ return false; };
  			var wishlistEventBody = '{"EntityDetails": {"id": "'+ StubHub.eventID + '"}}';
  			   $.ajax({
  				   url: wishlistAPI(u2_Guid),
  				   type: type,
  				   dataType: 'json',
  				   cache: false,
  				   data: wishlistEventBody,
  				   beforeSend: wishlistAjaxBeforeSendPost,
  				   success: wishlistSuccessPost,
  				   error: wishlistError
  				 });
  			   setOmnitureVariables({prop61:"Event Detail:" + SH.eventTitle+":Add to Wishlist button click", prop62:"Event Detail:Add to Wishlist button click", prop63:"Event Detail:"+SH.eventTitle});

  		};


  	   $("#wishlistbutton").live("click", function(){
//  		   console.log("wishlist button click");

  		   if ((typeof(u2_Guid) !== "undefined")  && (u2_Guid != "") ){
  			   //console.log("trying to post, u2_Guid:" + u2_Guid + " SH.wishlistAdded" + SH.wishlistAdded);
  				 if (SH.wishlistAdded == false){
  					 wishListAjaxAdd('POST', wishlistAjaxBeforeSendPost, wishlistSuccessPost, wishlistError);
  				 } else {
  					 //console.log('wishlist was added previously');
  				 }

  		 	   } else {
  		 		  //console.log("redirecting to sign in:" + addWishlistUrl);
  		 		   window.location.href=addWishlistUrl;
  		 	   }


  	   });

  	   $(".disableLink").live("click", function(){
  		   setOmnitureVariables({prop61:"Event Detail:" + SH.eventTitle+":Wishlisted button click", prop62:"Event Detail:Wishlisted button click", prop63:"Event Detail:"+SH.eventTitle});
  	   });

  	   function gup(name){
  		    name = name.replace(/[[]/, "\[").replace(/[]]/, "\]");
  		    var regexS = "[\?&]" + name + "=([^&#]*)";
  		    var regex = new RegExp(regexS);
  		    var results = regex.exec(window.location.href);
  		    if (results == null)
  		        return "";
  		    else
  		        return results[1];
  		};




  	var wishlist = function(){
//  		console.log("++++ check wishlist button status ++++ ");
  		 if ((typeof(u2_Guid) !== "undefined")  && (u2_Guid != "") ){
  			 //console.log("u2_Guid: " + u2_Guid);
  			 wishListAjax('GET', wishlistAjaxBeforeSendGet, wishlistSuccessGet, wishlistError);
  		 } else {
  	 		  //console.log("didn cookie GUID");
  	 		  showWLTooltip('wishlistNotAdded');
  	 	 }


  	}; 
  	
		$('#eventSummaryPanel').panel({panelId:'p-bg-grblu-panel',bgFullClass:'p-bg-grblu-center', bgBottomClass:'p-bg-grblu-bottom', bgTopClass:'p-bg-grblu-top'});
		checkCookie();
		wishlist();

		/* ======+====== begin exclusive code ======+====== */
		$("#eventSummaryPanel #exclusive").livequery( function() {
			var $summaryPanel = $("#p-bg-grblu-panel");
			$summaryPanel.addClass('p-exclusive');
			$(".p-exclusive-content").html($(".exclusivesContent").html());
			$(".exclusivesContent").html("");
			$(".p-subtitle .exclusiveSubtitle").html($(".p-exclusive-content .exclusiveSubtitle").html());
			$(".p-exclusive-content").html( $("#exclusiveGalleryTemplate").html()  + $(".p-exclusive-content").html());
			$("#exclusiveGalleryTemplate").html("");
			$("#exclusiveGallery").panel({panelId:'p-exclusive-gallery'});

			gotoSlide(1, $("#exclusiveGallery"));
			bindIcon($("#exclusiveGallery"));

			$(".enlargeContainerLink").click(function(){
				gotoSlide(parseInt($("#exclusiveGallery").find(".slideIndex").html()), $("#largeContainer"));

				$(".enlargeContainerLink").overlay({align:'center', closeSelector:'.closeLink', width:510, trigger:'load'});
				bindIcon($("#largeContainer"));
				bindPagi($("#largeContainer"));
				$("#largeContainer").panel({panelId:'p-exclusive-enlarge', panelClass:'p-panel-nested',  disableCssHack:true});


			});

			//create slideshow

			function bindIcon(obj){
				$(obj).find(".prevIcon").click(function(){
					var slideIndex = $(obj).find(".slideIndex").html();
					if(slideIndex==1){return false};
					slideIndex--;
					gotoSlide(slideIndex, $(obj));
				});

				$(obj).find(".nextIcon").click(function(){
					var slideIndex = $(obj).find(".slideIndex").html();
					if(slideIndex==$("#"+$(obj).find(".slideSrc").html()+" li").length){return false};
					slideIndex++;
					gotoSlide(slideIndex, $(obj));
				});

			}

			function bindPagi(obj){
				$(obj).find(".pagiNo a").click(function(){
					var slideIndex = $(this).html();
					$(obj).find(".slideIndex").html(slideIndex) ;
					gotoSlide(slideIndex, $(obj));
				});

			}
			function gotoSlide(index, obj){
				$(obj).find(".thumbnailFrame").attr("src", $("#"+$(obj).find(".slideSrc").html() + " li:eq("+ (index-1) +")").html());
				$(obj).find(".slideIndex").html(index);
				setPagi(parseInt(index), $(obj));
			}

			function setPagi(index, obj){
				//todo:disable prev next icon if 1st last

				var total = $("#"+$(obj).find(".slideSrc").html()+" li").length;

				if (index==1){
						$(".prevIcon").removeClass('active-left-arrow').addClass('inactive-left-arrow');
				}
				if (index!=1){
					$(".prevIcon").removeClass('inactive-left-arrow').addClass('active-left-arrow');
				}
				if (index==total){
					$(".nextIcon").removeClass('active-right-arrow').addClass('inactive-right-arrow');
				}
				if (index!=total){
					$(".nextIcon").removeClass('inactive-right-arrow').addClass('active-right-arrow');
				}

				if($(obj).find(".slideSrc").html()=="exclusivePhotoList"){ // check if it is largeslide show container
					if(total<=5){
						startIndex=1;
						endIndex = total;
					}
					else if(index+2>=total){
						startIndex = total-4;
						endIndex = total;
					}
					else{
						var startIndex = index<3 ? 1 : (index-2);
						var endIndex = index<=3 ? 5 : index+2;
					}
				}
				else{ // else it is in thumbnail container
					if(total<=4){
						startIndex=1;
						endIndex = total;
					}
					else if(index+2>=total){
						startIndex = total-3;
						endIndex = total;
					}
					else{
						var startIndex = index==1 ? 1 : (index-1);
						var endIndex = index==1 ? 4 : index+2;
					}
				}
				var pageHtml="";
				for(var i=startIndex; i<=endIndex; i++){
					if(i==index){
						pageHtml += "<span class='pagiNo'><b>"+(i)+"</b></span>";
					}
					else{
						pageHtml += "<span class='pagiNo'><a href='javascript:void(0)'>"+(i)+"</a></span>";
					}
					if(i!=endIndex){
						pageHtml += " | ";
					}
				}
				$(obj).find(".exlpagi").html(pageHtml);
				bindPagi($(obj));

			}
			$('#toogleExclusive').toggle(
					function(){
						$(".p-exclusive .p-subtitle a.arrow span").removeClass('arrow-7-e').addClass('arrow-7-s');
						$summaryPanel.removeClass('p-exclusive').addClass('p-exclusive-toggle');
						$("#exclusive #seeMoreExlTxt").html(ComparePopup.seeLessExcl);
					},
					function(){
						$(".p-exclusive-toggle .p-subtitle a.arrow span").removeClass('arrow-7-s').addClass('arrow-7-e');
						$summaryPanel.removeClass('p-exclusive-toggle').addClass('p-exclusive')
						$("#exclusive #seeMoreExlTxt").html(ComparePopup.seeMoreExcl);
					}
			);

			/* ======+====== end exclusive code ======+====== */
		});

		$("#fanProtectLink, #fanProtectLinkPA").overlay({align:'relative',width:440,trigger:'click', source:'/help/services/popUp?nodeDesc=fanprotect_popup'});
		//$("#fanProtectLinkPA").overlay({align:'relative',width:440,trigger:'click', source:'/help/services/popUp?nodeDesc=fanprotect_popup'});
		$("#seatingGuide").overlay({align:'relative',source:'#seatingNotesdiv',width:440, trigger:'click', preferedPosition:'below', preferedAlignment:'right'});

		$("#seatingGuide").bind("click", function(){
			//setOmnitureVariables({eVar43:"BUYMAP - Seat Nts"});
			setOmnitureVariables({prop61:"Event Detail:" + SH.eventTitle+":View seating guide Link click", prop62:"View seating guide Link click", prop63:"Event Detail:"+SH.eventTitle});
		});


		/* EVENTPAGE-776 FR code changes start*/
		function updateEventInfo(){
			try{
					var eventTitle = $("#eventTitleInfo").text();
					if(SH.event.visitingTeamId != 'undefined' && SH.event.visitingTeamId !=""){
						if(SH.event.actPrimary != "" && SH.event.homeTeamGenreUrl != ""){
							eventTitle = eventTitle.replace(SH.event.actPrimary, '<a class="homeTeamLink" href="/'+SH.event.homeTeamGenreUrl+'/">'+SH.event.actPrimary+'</a>');
						}
						if(SH.event.actSecondary != "" && SH.event.visitingTeamUrl != ""){
							eventTitle = eventTitle.replace(SH.event.actSecondary, '<a class="visitingTeamLink" href="/'+SH.event.visitingTeamUrl+'/">'+SH.event.actSecondary+'</a>');
						}
						$("#eventTitleInfo").html(eventTitle);
					}else{
						if(SH.event.actPrimary != "" && SH.event.homeTeamGenreUrl != ""){
							var ticketTextindex = eventTitle.lastIndexOf(" Tickets");
							var hyperedLinkedText = eventTitle.substring(0, ticketTextindex);
							eventTitle = eventTitle.replace(hyperedLinkedText, '<a class="homeTeamLink" href="/'+SH.event.homeTeamGenreUrl+'/">'+hyperedLinkedText+'</a>');
						}
						$("#eventTitleInfo").html(eventTitle);
					}
					$("#eventTitleInfo").removeClass("hideOnLoad");

			}catch(e){
			}finally{
				$("#eventTitleInfo").removeClass("hideOnLoad");
			}
		};
			updateEventInfo();

			$("a.homeTeamLink").click(function(e){
				e.preventDefault();
				setOmnitureVariables({prop61:"event title Link Click|" +SH.event.actPrimary , prop62:"event title Link Click", prop63:"event title Link Click|"+SH.tracking.pageName});
				var destination = $(this).attr('href');
				  setTimeout(function() { document.location.href = 	destination ; }, 1000);
			});

			$("a.visitingTeamLink").click(function(e){
				e.preventDefault();
				setOmnitureVariables({prop61:"event title Link Click|" +SH.event.actSecondary , prop62:"event title Link Click", prop63:"event title Link Click|"+SH.tracking.pageName});
				var destination = $(this).attr('href');
				setTimeout(function() { document.location.href = 	destination ; }, 1000);
			});

			/* EVENTPAGE-776 FR code changes end*/

			$("a.selleventlink").click(function(e){
				e.preventDefault();
				setOmnitureVariables({prop61:"Event Detail:" + SH.eventTitle+":Sell for this event Link click", prop62:"Event Detail:Sell for this event Link click", prop63:"Event Detail:"+SH.eventTitle});
				var destination = $(this).attr('href');
				setTimeout(function() { document.location.href = 	destination ; }, 1000);
			});


			$("#viewHistory .eventlist li").click(function(e){
				var index = $("#viewHistory .eventlist li").index(this);
				index = parseInt(index,10)+1;
				e.preventDefault();
				setOmnitureVariables({prop61:"Event Detail:" + SH.eventTitle+":Browse History:"+index, prop62:"Event Detail:Browse History:"+index, prop63:"Event Detail:"+SH.eventTitle});
				var destination = $(this).children("a").attr('href');
				setTimeout(function() { document.location.href = 	destination ; }, 1000);
			});
			$("a.reportMapError").click(function(){
				setOmnitureVariables({prop61:"Event Detail:" + SH.eventTitle+":Report map errors Link click", prop62:"Event Detail:Report map errors Link click", prop63:"Event Detail:"+SH.eventTitle});
			});
		//Events associated with Help overlay and formatting
		//$(".formathelp").overlay({align:'relative', overlayId:'formatHelpLayer',width:510});


		var modalAlert = typeof(isEventAlert) !='undefined' && isEventAlert;
		var eventInfo = {align:'relative',width:400,preferedAlignment:'right'};
		if(modalAlert) {
		                     eventInfo = {overlayId:"eventInfoOverlayId",modal:true,showCloseIcon:false,width:400,closeSelector:'#eventInfoLayer #btnOk',
		                                 close:function(){
		                                       SH.closeEventInfo = true;
		                                 }
		                     }
		            }

		$("#eventInfoLink").overlay(eventInfo);
		$("#continue").overlay({modal:true,align:'centered',width:400,source:'#continuediv',closeSelector:'#continuediv .Cancel'});
		$("#seatingNote").overlay({modal:false,align:'relative',source:'#seatingNotesdiv',width:440});

		//RCP for widget
		$(".p-widget").panel({bgTopClass:'p-bg-hdrblu-lrg p-hdr-lrg',	blSliceClass:'p-collapsable', brSliceClass:'p-collapsable'});

		//toogleCookieZone
		$("#viewHistory .eventlist li").live("mouseover", function(){
			$(this).addClass('hover');
		});
		$("#viewHistory .eventlist li").live("mouseout", function(){
			$(this).removeClass('hover');
		});
		$("#ticketFeaturesLink").click( function() {
			toggleCookie(this, "sf");
		});
		$("#zoneLink").click( function() {
			toggleCookie(this, "z");
		});
		$("#upcomingLink").click( function() {
			toggleCookie(this, "ue");
		});
		$('#mapZoomInfo').bind('click', function(){
			$.writeCookielet("STUB_PERSISTENT","mz",1, 1080);
		});
		$('#btnMapOk').live('click', function(){
			$('#seatMapOverlay').addClass('p-offscreenOnLoad');
			triggerOmnitureEvent('event54','Help overlay selection');
			$.writeCookielet("STUB_SESSION","smz",1);
		});
		$('#next').live('click', function(){
			triggerOmnitureEvent('scAdd','Shopping cart adds');
		});


		var priceAlert = function() {
		    try {
		        var s = s_gi(s_account);
		        s.objectId = "PA654321";
		        s.tl(this, 'o', 'Price Alert Button');
		    } catch (e) {
		    }
		    //empty div every time when setpricealert button is clicked
		    $('#priceAlertDiv').html();
		    $.getJSON(priceAlertUrl + '&gotoUrl=' + encodeURIComponent(setAlertParam(1, location.href)) + '&fromSetAlert=1&action=view&format=json&jsoncallback=?', function(resp) {
		        $('#priceAlertDiv').html(resp.data);
		        if ((typeof (isSignin) != 'undefined') && (isSignin == true)) {
		        	location.href = gotoUrl.replace('&amp;', '&');
		        }
		        else {
		            $('#setPriceAlert').overlay({ modal: true, overlayId: 'priceAlertLayer', width: 600, source: '#priceAlertDiv', closeSelector:'.cancelLink', trigger: 'load', open: validateAfterOverlay});
		            $('#price_error').attr("style", "margin-left: 10px;display:none;");
		            $('#zone_error').attr("style", "display:none;");
		        }
		    });
		};
		var validateAfterOverlay = function(elem,orientation,opts){
            if (typeof shMultiCurrency === 'object') {
               shMultiCurrency.bindConvertorFromSelectCurr( { selector: '#price', bindPriceValidate: false });
			}
		};
		$('#setPriceAlert').livequery('click', function() {
			triggerOmnitureEvent('event37','Price alert');
			priceAlert();
		});
		
var valueMessagePopup = function() {
	$('#popupTestbutton').overlay({ modal: true,  closeOnClickOutside:true,style:'box',showCloseIcon:true,overlayId: null, overlayClass:'value-message-popup',width: 670, source: '#value_message_popup_div',trigger: 'load'});

};
		
		$('#linkPriceAlert').livequery('click', function() {
			priceAlert();
		});



		$('#removeAlert').livequery('click', function() {
		    //empty div every time when removeAlert button is clicked
		    $('#removeAlertDiv').html();
		    $.getJSON(deleteAlertUrl + '&gotoUrl=' + encodeURIComponent(setAlertParam(2, location.href)) + '&fromSetAlert=1&action=view&format=json&jsoncallback=?', function(resp) {
		        $('#removeAlertDiv').html(resp.data);
		        if ((typeof (isSignin) != 'undefined') && (isSignin == true)) {
		            var topPosition = $(window).height() / 2 - 100;
		            var leftPosition = $(window).width() / 2 - 350;
		            popUpSignIn = window.open(gotoUrl.replace('&amp;', '&'), 'overlaySignIn', 'width=700,height=400,top=' + topPosition + ',left=' + leftPosition + 'alwaysRaised=yes,scrollbars=no,status=no,titlebar=no,toolbar=no,location=no,menubar=no,copyhistory=no,directories=no');
		        }
		        else {
		            $('#removeAlert').overlay({ modal: true, overlayId: 'removeAlertLayer', width: 390, closeSelector: '#deletePriceAlert #btnNo', source: '#removeAlertDiv', trigger: 'load' });
		            $("#removeAlertDiv #btnYes").attr("type", "button");
		        }
		    });
		});

		$('#editAlert').livequery('click', function() {
		    //empty div every time when setpricealert button is clicked
		    $('#priceAlertDiv').html();
		    $.getJSON(priceAlertUrl + '&gotoUrl=' + encodeURIComponent(setAlertParam(1, location.href)) + '&action=view&format=json&jsoncallback=?', function(resp) {
		        $('#priceAlertDiv').html(resp.data);
		        if ((typeof (isSignin) != 'undefined') && (isSignin == true)) {
		        	location.href = gotoUrl.replace('&amp;', '&');
		        }
		        else {
		            $('#editAlert').overlay({ modal: true, overlayId: 'priceAlertLayer', closeSelector: '.cancelLink', width: 600, source: '#priceAlertDiv', trigger: 'load', open: validateAfterOverlay });
		            $('#price_error').attr("style", "margin-left:10px;display:none;");
		            $('#zone_error').attr("style", "display:none;");
		        }
		    });
		});

		/* ---------------- Function to set alert param -----------------------*/
		function setAlertParam(mode, gotoURL) {
		    var alertVar = 'setAlert=' + mode;
		    if (gotoURL.match(/setAlert/) == 'setAlert') {
		        if (gotoURL.match(/setAlert=0/) == 'setAlert=0')
		            return (gotoURL.replace('setAlert=0', alertVar));
		        else if (gotoURL.match(/setAlert=1/) == 'setAlert=1')
		            return (gotoURL.replace('setAlert=1', alertVar));
		        else if (gotoURL.match(/setAlert=2/) == 'setAlert=2')
		            return (gotoURL.replace('setAlert=2', alertVar));
		    }
		    else
		        return ((gotoURL.indexOf('?') != '-1') ? ((gotoURL.indexOf('?') == ((gotoURL.length) - 1)) ? (gotoURL + alertVar) : (gotoURL + '&' + alertVar)) : (gotoURL + '?' + alertVar));
		}
		/* ---------------------------------------------------------------------- */
		//call to js function
		$("#compareTicket a.remLink").livequery("click", function(){
			var remLinkNameValue = $(this).attr('name');
			$('input.ticket[value='+ remLinkNameValue +']').attr('checked', false);
			removeCompareItem(this);
		});
		//For UK - EDP Pages if SetAlert not get display event heading panel display change
		if($("#setPriceAlert").length==0){$("#eventSummaryPanel div.p1").css("width","390px");}

		if($("#alertConfirmationMessage")){
		      //$("#alertConfirmationMessage").panel();
		 };

		//Feedback functionality
		var uvOptions = {};
		(function() {
			var uv = document.createElement('script'); uv.type = 'text/javascript'; uv.async = true;
			uv.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'widget.uservoice.com/hwPKAA8vA3k2s09sxdGE1Q.js';
			var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(uv, s);
			}
		)();


		$('#compare').bind('click',function() {
			triggerOmnitureEvent('event35','Compare button')

			var count = $(":checkbox:checked.ticket").length;
			if (count <2 || count > 5){
				$("#compareError").removeClass('hideOnLoad');
				return false;
			}else{
				$("#compareError").addClass('hideOnLoad');
			}

			buyQuantity = $('#quantitySelect').val();

			comparableTickets = [];

			$('#ticketListTable .ticket:checked').each(function(){

				var tr = $(this).parent().parent(),
				    $tr = $(tr);

				if (buyQuantity != 'all'){
					buyQuanity = ($tr.find('.q_cont .q').html());
				}

				var compareObj = {
						listingId:	$(this).val(),
                        currentPrice: $tr.find('.p1').text(),
						venueConfigSectionAlias:	($tr.find('.sectionName').html()),
						rowDesc:	($tr.find('.p_cont .ticketRow').html()),
						seats:	($tr.find('.st').html()),
						quantity:	($tr.find('.p_cont span.ticketQty').html()),
						split:	($tr.find('.spl').html()),
						isCharity:	$tr.find('.charity').html(),
						isExclusiveOffer:	$tr.find('.exclusive').html(),
						isExcludeObstructed:	$tr.find('.obstructed').html(),
						isWheelChair:	$tr.find('.wheelchair').html(),
						isAlcholFree:	$tr.find('.alcoholFree').html(),
						isParkingPassIncluded:	$tr.find('.parking').html(),
						isPiggyback:	$tr.find('.piggyback').html(),
						isStudentFacultySeat:	$tr.find('.facultyExclude').html(),
						isSeniorYouthChild:	$tr.find('.seniorExclude').html(),
						isAisle:	$tr.find('.aisle').html(),
						listingAttributeIdList: null,
						currencyCode:		$tr.find('.q_cont').attr("currencyCode"),
                        faceValue: $tr.find('.fv').text(),
                        deliveryMethod: $tr.find('.deliveryMethod').text()
				};
				comparableTickets.push(compareObj);
			});



			$('#compareTicket').html(renderListing());
			$(".compareTable tr:even").each(function(){
				$(this).find("td:first").addClass("features");
				$(this).find("td:gt(0)").addClass("features2");
			});
			$(".compareTable tr:odd").each(function(){
				$(this).find("td:first").addClass("features3");
				$(this).find("td:gt(0)").addClass("features1");
			});
			var compareLayerWidth = 910 - (5 - comparableTickets.length)*15;
			$("#compare").overlay({modal:true,draggable:true,align:'centered',overlayId:'compareTicketsLayer',width:compareLayerWidth,source:'#compareTicketDiv',trigger:'load'});

			try{
				var s=s_gi(s_account);
				var nameArr = pageName.split("/");
				s.pageName = nameArr[0] + "/" +nameArr[1] + "/compare_tickets";
				s.tl();
			}catch(e){
			}
			//This css is applied , in case after content is loded a white border is mising on left side of overlay
			// By applying zoom css, it works fine.
			$(".ov-slice-tr").attr("style", "zoom:1;");
		});

		$("#compareTicket .btn-sprite-buy").livequery('click', function(){
			openCheckout($(this).attr("txtId"));
		});

		//set 'sell for this event' middle aligned if, event info link is absent
		if(typeof(EventInfoflag) != "undefined" && EventInfoflag == "false"){
			$("#sellEvent").css("margin-top","12px");
		}

		if(typeof(isPriceAlertsEnabled) != "undefined" && isPriceAlertsEnabled == "true"){
			$("#fanProtectLink").removeClass("hideOnLoad");
		}

		$(document).ready(function() {
			
		    updateWidgets();
		    
		    if (modalAlert) {
		        $("#eventInfoLink").trigger('click');
		    }
		    else if(typeof(isValueMessagePopupTest) != "undefined" && isValueMessagePopupTest == true)
		    {   	
		    	valueMessagePopup();		   
		    }
		    if (typeof (TktFilterMapFlashObj) != "undefined")
		        $("#tktFilterMap").flash(TktFilterMapFlashObj, { version: 8 });
		    if (typeof (TktListingsMapFlashObj) != "undefined")
		    	$("#tktListingsMap").flash(TktListingsMapFlashObj, { version: 8 });

		    if ($.query.get('setAlert') == 1) {
            	//empty div every time when setpricealert button is clicked
    		    $('#priceAlertDiv').html();
    		    $.getJSON(priceAlertUrl + '&gotoUrl=' + encodeURIComponent(setAlertParam(1, location.href)) + '&fromSetAlert=1&action=view&format=json&jsoncallback=?', function(resp) {
    		        $('#priceAlertDiv').html(resp.data);
    		        if ((typeof (isSignin) != 'undefined') && (isSignin == true)) {
    		            location.href = gotoUrl.replace('&amp;', '&');
    		        }
    		        else {
                        $('#priceAlert').overlay({ modal: true, overlayId: 'priceAlertLayer', width: 600, source: '#priceAlertDiv', trigger: 'load', open: validateAfterOverlay });
    		            $('#price_error').attr("style", "margin-left: 10px;display:none;");
    		            $('#zone_error').attr("style", "display:none;");
    		        }
    		    });

            } else if ($.query.get('setAlert') == 2) {
                $.getJSON(deleteAlertUrl + '&fromSetAlert=1&action=view&isDelete=1&format=json&jsoncallback=?', function(resp) {
                    $('#removeAlertDiv').html(resp.data);
                    if (typeof (isSignin) == 'undefined') {
                        $('#removeAlertDiv').overlay({ modal: true, overlayId: 'removeAlertLayer', width: 390, closeSelector: '#deletePriceAlert #btnNo', source: '#removeAlertDiv', trigger: 'load' });
                        $("#removeAlertDiv #btnYes").attr("type", "button");
                    }
                });
            }

            $(window).unload(function() {
                if (typeof popUpSignIn != 'undefined' && typeof popUpSignIn.close != 'undefined') {
                	popUpSignIn.close();
                }
            });

            /*Primary partnership updates*/
        	//Tracking for see tickets button and upcoming events
            $("#primarySeeTickets").click(function(){
           	 	setOmnitureVariables({prop61:"Plinks_Genre:"+SH.genreID+":See Tickets Button Clicked", prop62:"Plinks_Genre:See Tickets Button Clicked", prop63:"Plinks_Genre:"+SH.genreID+":"+StubHub.tracking.pageName});
            });
            
            $("#noListingsUpcomingEvents").live("click",function(e){
            	e.preventDefault();
            	var destination = $(this).attr('href');
            	
           	 	setOmnitureVariables({prop61:"Plinks_Genre:"+SH.genreID+":Upcoming Events Button Clicked", prop62:"Plinks_Genre:Upcoming Events Button Clicked", prop63:"Plinks_Genre:"+SH.genreID+":"+StubHub.tracking.pageName});
           	 	setTimeout(function() { document.location.href = destination ; }, 500);
            });

		});
		
});
})(jQuery, StubHub);
(function($) {
	$(function() {
		var delete_timer;
		function toggleZoneLayer(val){
			if(val == "0") {
				$("#priceAlert .zonewrapper").show();
			} else {
				$("#priceAlert .zonewrapper").hide();
			}
		}
		function enableButton() {
			$("#priceAlert #setAlert").removeClass("disabled");
		}

        function getInputPrice () {
           var convertedPrice = $('#priceHint').attr('data-origin-price'),
               inputPrice = new Number($('#price').priceVal()),
               price = inputPrice;

           // user did not input anything.
           if (inputPrice <= 0 || isNaN(inputPrice)) {
              return '';
           }

           if (convertedPrice) {
              price = parseFloat(convertedPrice);
           }

           return price > 0 ? ('' + price) : '';

        }

		function isFormValid(allzoneval, selectedCb, price){
		   //form validation using jquery
		   var priceObj = $("#price");
		   if( price == "" || price == "0" || !IsNumeric(price) ){
				$("#price_error").removeClass("hideOnLoad").attr("style","margin-left: 10px;");
				return false;
		   }else{

				$("#price_error").addClass("hideOnLoad").attr("style","margin-left: 10px;");
		   }

		   //checkbox validation using jquery
		   if(allzoneval == "0" && selectedCb == ""){
				$('#zone_error').removeClass("hideOnLoad").removeAttr("style");
				$("#priceAlert #setAlert").removeClass("disabled");
				return false;
		   }else{
				$("#zone_error").addClass("hideOnLoad");
		   }

		   return true;
		}

		function IsNumeric(sText){
		   var ValidChars = "0123456789.$";
		   var IsNumber=true;
		   var Char;
		   var isDollar = 0;
		   var re = new RegExp(",","g");
		   sText = sText.replace(re,"");

		   for (i=0; i<sText.length && IsNumber == true; i++){
		      Char = sText.charAt(i);
			  if(Char == '$')
				isDollar += 1;
		      if (ValidChars.indexOf(Char) == -1 || isDollar >1){
		    	 IsNumber = false;
	          }

		   }

		   return IsNumber;
	    }

		function appendF(url){
			var param = '?f=1';
			if(url != ''){
				var f = queryString(url,'f');
				if(typeof(f) == 'undefined')
					param = '&f=1';
				else
					param = '';
			}
			return param;
		}
		function queryString(url, ji) {
			hu = url.substring(1);
			gy = hu.split("&");
			for (i=0;i<gy.length;i++) {
				ft = gy[i].split("=");
				if (ft[0] == ji) {
					return ft[1];
				}
			}

}
/* ---------------- Function to set alert param -----------------------*/

function setAlertParam(mode, gotoURL) {
    var alertVar = 'setAlert=' + mode;
    if (gotoURL.match(/setAlert/) == 'setAlert') {
        if (gotoURL.match(/setAlert=0/) == 'setAlert=0')
            return (gotoURL.replace('setAlert=0', alertVar));
        else if (gotoURL.match(/setAlert=1/) == 'setAlert=1')
            return (gotoURL.replace('setAlert=1', alertVar));
        else if (gotoURL.match(/setAlert=2/) == 'setAlert=2')

            return (gotoURL.replace('setAlert=2', alertVar));
    }

    else
        return ((gotoURL.indexOf('?') != '-1') ? ((gotoURL.indexOf('?') == ((gotoURL.length) - 1)) ? (gotoURL + alertVar) : (gotoURL + '&' + alertVar)) : (gotoURL + '?' + alertVar));
}
/* ---------------------------------------------------------------------- */


		// put bindings here;
		$("#priceAlert form input:radio").live('click', function(){
			toggleZoneLayer(this.value);
		});

		$("#priceAlert form input:radio").livequery(function(){
			toggleZoneLayer(this.checked?this.value:"");
		});

		$("#priceAlert #container").livequery(function(){
			if(typeof(pa_disableForm) != 'undefined' && pa_disableForm) {

				var el = $('<div></div>').appendTo('#priceAlert')
				.addClass('formdisabled').css({
					width: $(this).width(),
					height: $(this).height(),
					top: $(this).position().top,
					left: $(this).position().left
				});
				//bgiframe hides the drop down
				//el.bgiframe();
				$('#priceAlert form select').attr("disabled","disabled");
				$('#setPriceAlert').addClass('disabled');
				$('#container').attr('disabled','true');
			}
		});

		$('#priceAlert').live("keypress", function(e){
			   code= (e.keyCode ? e.keyCode : e.which);
			   if (code == 13) {
				   $("#setAlert").click();
			   }
			});

		$("#priceAlert #setAlert").live("click", function(){
			var realPrice = getInputPrice();

			if($(this).hasClass("disabled")) {
				return false;
			}
			$(this).addClass("disabled");
			//take out the value for all zone
			var allzoneval = "1";
			if($("#priceAlert .zonewrapper").is(':visible')){
				allzoneval = "0";
			}

			var submitUrl = "&quantity="+$("#quantity").val()+"&price="+realPrice+"&allZoneInd="+allzoneval;
			var selectedCb = "";
			var re = new RegExp("venueZoneId_","g");

			$('input:checkbox').each( function() {
				if(this.checked){
					selectedCb += "&" + this.id + "=" + this.value;
				}
			});


			if(!isFormValid(allzoneval, selectedCb, realPrice)){
				$(this).removeClass("disabled");
				return false;
			}

			submitUrl += selectedCb.replace(re,"Zone");

			 $("#priceAlertDiv #priceAlert").html("<div id='priceAlert' style='height:46px;padding-top:15px;'><div id='progressSection' style='display:inline'>" + $("#priceAlert #progressSection").html() + "</div></div>");
            var submit_timer = window.setTimeout(function() {
            $.getJSON(priceAlertUrl + submitUrl + '&gotoUrl=' + encodeURIComponent(setAlertParam(1, location.href)) + '&action=submit&format=json&jsoncallback=?', function(resp) {
                    $("#priceAlertDiv").html(resp.data);
                    $("#priceAlert #progressSection").show();
                    if ((typeof (isSignin) != 'undefined') && (isSignin == true)) {
                    	location.href = gotoUrl.replace('&amp;', '&');
                    }
                    else {
                        if (typeof (pa_isSubmitSuccessful) != "undefined" && pa_isSubmitSuccessful) {
                            try {
                                s.events = 'event37';
                                s.t();
                            }
                            catch (e) { }
                            //if (pa_isFromMyAccount && typeof (pa_paramMap) != "undefined" && pa_paramMap) {
                            if (pa_isFromMyAccount == true) {
                                var url = 'https://' + window.location.hostname + '/myaccount/pricealerts';
                                //url += '/' + pa_paramMap.pageNum + '/' + pa_paramMap.eventId + '/edit/1';
                                location.href = url;
                            }
                            else {
                                var parentLocation = location.href;
                                if (parentLocation.match(/setAlert/) == 'setAlert') {
                                    parentLocation = parentLocation.replace('setAlert=1', 'setAlert=0');
                                    parentLocation = parentLocation.replace('setAlert=2', 'setAlert=0');
                                    parentLocation = parentLocation.replace('setAlert=3', 'setAlert=0');
                                }
                                location.href = parentLocation + appendF(window.location.search);
                            }
                        }
                        else {
                            $("#priceAlert #progressSection").hide();
                        }
                    }
                });
            }, 1500);
        });

		//check if genrePriceAlertBaseUrl already has genre_id
		function checkEventId(){
			//deleteAlertUrl is from event page
			var eventIdExist = deleteAlertUrl.substr(priceAlertUrl.indexOf("event_id=") + 9);
			var x1 = priceAlertUrl.indexOf("event_id=") + 9;
			var x2= priceAlertUrl.indexOf("&amp;gotoUrl");

			if(typeof(event_id) == "undefined"){
				event_id = priceAlertUrl.substr(x1,x2-x1);
			}

			if(eventIdExist == ""){
				deleteAlertUrl = deleteAlertUrl + "event_id=" + event_id;
			} else {
				deleteAlertUrl = deleteAlertUrl;
			}


		}

		$('#removeAlert').live('click', function() {

			if(typeof(event_id) == "undefined"){
				checkEventId();
			}

		    $('#removeAlertDiv').html();
		    $.getJSON(deleteAlertUrl + '&gotoUrl=' + encodeURIComponent(setAlertParam(2, location.href)) + '&fromSetAlert=1&action=view&format=json&jsoncallback=?', function(resp) {
		        $('#removeAlertDiv').html(resp.data);
		        if ((typeof (isSignin) != 'undefined') && (isSignin == true)) {
		        	location.href = gotoUrl.replace('&amp;', '&');
		        }
		        else {
		            $('#removeAlertDiv').overlay({ modal: true, overlayId: 'removeAlertLayer', width: 390, closeSelector: '#deletePriceAlert #btnNo', source: '#removeAlertDiv', trigger: 'load' });
		            $("#removeAlertDiv #btnYes").attr("type", "button");
		        }
		    });
		});



        $("#deletePriceAlert #btnYes").live("click", function() {
            $("#deletePriceAlert #progressSection").show();
            $("#deletePriceAlert #deleteSection").hide();
            var delete_timer = window.setTimeout(function() {
            	if(typeof deleteAlertUrl != "undefined"){
		            $.getJSON(deleteAlertUrl + '&gotoUrl=' + encodeURIComponent(setAlertParam(2, location.href)) + '&action=submit&format=json&jsoncallback=?', function(resp) {
		                    $("#removeAlertDiv").html(resp.data);
		                    $("#deletePriceAlert #progressSection").show();

		                    if ((typeof (isSignin) != 'undefined') && (isSignin == true)) {
		                    	location.href = gotoUrl.replace('&amp;', '&');
		                    }
		                    else {
		                        //if (pa_isFromMyAccount && typeof (pa_paramMap) != "undefined" && pa_paramMap) {
		                    	if (pa_isFromMyAccount == true && pa_isSubmitSuccessful) {
		                            var url = 'https://' + window.location.hostname + '/myaccount/pricealerts';
		                            //url += '/' + pa_paramMap.pageNum + '/' + pa_paramMap.eventId + '/delete/1';
		                            location.href = url;
		                        } else {
		                            var parentLocation = location.href;
		                            if (parentLocation.match(/f=1/) == 'f=1') {
		                            	parentLocation = parentLocation.replace('?f=1', '');
		                            	parentLocation = parentLocation.replace('&f=1', '');
		                            }
		                            if (parentLocation.match(/setAlert/) == 'setAlert') {
		                                parentLocation = parentLocation.replace('setAlert=1', 'setAlert=0');
		                                parentLocation = parentLocation.replace('setAlert=2', 'setAlert=0');
		                            }
		                            location.href = parentLocation + appendF(window.location.search);
		                        }
		                    }
		                    $("#deletePriceAlert #btnNo").trigger("click");
		                });
            	}

            }, 1500);
            //return false;
		});
	});
})(jQuery);
(function($) {
    $(function() {
        var delete_timer;
        function enableButton() {
            $("#priceAlert #setAlert").removeClass("disabled");
        }

        function appendF(url) {
            var param = '?f=1';
            if (url != '') {
                var f = queryString(url, 'f');
                if (typeof (f) == 'undefined')
                    param = '&f=1';
                else
                    param = '';
            }
            return param;
        }
        function queryString(url, ji) {
            hu = url.substring(1);
            gy = hu.split("&");
            for (i = 0; i < gy.length; i++) {
                ft = gy[i].split("=");
                if (ft[0] == ji) {
                    return ft[1];
                }
            }
        }

        /* ---------------- Function to set alert param -----------------------*/
        function setAlertParam(mode, gotoURL) {
            var alertVar = 'setAlert=' + mode;
            if (gotoURL.match(/setAlert/) == 'setAlert') {
                if (gotoURL.match(/setAlert=0/) == 'setAlert=0')
                    return (gotoURL.replace('setAlert=0', alertVar));
                else if (gotoURL.match(/setAlert=1/) == 'setAlert=1')
                    return (gotoURL.replace('setAlert=1', alertVar));
                else if (gotoURL.match(/setAlert=2/) == 'setAlert=2')
                    return (gotoURL.replace('setAlert=2', alertVar));
            }
            else
                return ((gotoURL.indexOf('?') != '-1') ? ((gotoURL.indexOf('?') == ((gotoURL.length) - 1)) ? (gotoURL + alertVar) : (gotoURL + '&' + alertVar)) : (gotoURL + '?' + alertVar));
        }
        /* ---------------------------------------------------------------------- */

        /* --------------------- Disbale alerts when max reached -----------------------*/
        $("#setGenreAlertDiv #setEventAlertOverlay").livequery(function() {
            if (typeof (pa_disableForm) != 'undefined' && pa_disableForm) {
                var el = $('<div></div>').appendTo('#setGenreAlertDiv')
				.addClass('formdisabled').css({
				    width: $(this).width(),
				    height: $(this).height(),
				    top: $(this).position().top,
				    left: $(this).position().left
				});
                $("#setGenreAlertDiv button#setAlert").addClass('disabled');
            }
        });

        $("#setGenreAlertDiv #setAlert").live("click", function() {
            //if ($(this).hasClass("disabled")) {
            if ($(this).isSpriteBtnDisabled()) {
                return false;
            }

            //$(this).addClass("disabled");
           $(this).disableSpriteBtn();

            var submitUrl = "&eventWithTicketOnlyInd=" + $('input:radio[name=eventWithTicketOnlyInd]:checked').val() + "&geoNodeID=" + $('input:radio[name=geoNodeID]:checked').val();
            var submit_timer = window.setTimeout(function() {
            $.getJSON(genreAlertUrl + submitUrl + '&fromSetAlert=1&mode=2&action=' + genreAlertMode + '&format=json&gotoUrl=' + encodeURIComponent(setAlertParam(1, location.href)) + '&jsoncallback=?', function(resp) {
                    $("#setGenreAlertDiv").html(resp.data);
                    $("#genreEventAlert #progressSection").show();
                    if ((typeof (isSignin) != 'undefined') && (isSignin == true)) {
                    	location.href = gotoUrl.replace('&amp;', '&');
                    }
                    else {
                        if (typeof (pa_isSubmitSuccessful) != "undefined" && pa_isSubmitSuccessful) {
                            try {
                                s.events = 'event42';
                                s.t();
                            }
                            catch (e) { }
                            if (typeof (pa_isFromMyAccount) != "undefined" && pa_isFromMyAccount && typeof (pa_paramMap) != "undefined" && pa_paramMap) {
                                var url = 'https://' + window.location.hostname + '/myaccount/myaccteventalert';
                                url += '/' + pa_paramMap.pageNum + '/' + pa_paramMap.genreId + '/edit/1';
                                location.href = url;
                            }
                            else {
                                var parentLocation = location.href;
                                if (parentLocation.match(/setAlert/) == 'setAlert') {
                                    parentLocation = parentLocation.replace('setAlert=1', 'setAlert=0');
                                    parentLocation = parentLocation.replace('setAlert=2', 'setAlert=0');
                                    parentLocation = parentLocation.replace('setAlert=3', 'setAlert=0');
                                }
                                location.href = parentLocation + appendF(window.location.search);
                            }
                        }
                        else {
                            $("#genreEventAlert #progressSection").hide();
                            alert("here!! not succesful");
                        }
                    }
                });
            }, 1500);
        });

        $("#removeGenreAlertDiv button#btn-yes").live("click", function() {
            $("#deleteEventAlertOverlay #progressSection").show();
            $("#deleteEventAlertOverlay #deleteSection").hide();
            var delete_timer = window.setTimeout(function() {
            $.getJSON(deleteGenreAlertUrl + '&fromSetAlert=1&mode=2&action=3&isDelete=1&format=json&gotoUrl=' + encodeURIComponent(setAlertParam(2, location.href)) + '&jsoncallback=?', function(resp) {
            $("#removeGenreAlertDiv").html(resp.data);
                    if ((typeof (isSignin) != 'undefined') && (isSignin == true)) {
                     	location.href = gotoUrl.replace('&amp;', '&');
                    }
                    else {
                        if (typeof (pa_isFromMyAccount) != "undefined" && pa_isFromMyAccount && typeof (pa_paramMap) != "undefined" && pa_paramMap) {
                            var url = 'https://' + window.location.hostname + '/myaccount/myaccteventalert';
                            url += '/' + pa_paramMap.pageNum + '/' + pa_paramMap.genreId + '/delete/1';
                            location.href = url;
                        }
                        else
                        {
                            $("#removeGenreAlertDiv #progressSection").html("<img src='/resources/mojito/img/pattern/phoenix/throbber_24.gif'/> We\'re deleting your event alert.");
                            $("#removeGenreAlertDiv #progressSection").show();
                            var parentLocation = location.href;
                            if (parentLocation.match(/setAlert/) == 'setAlert') {
                                parentLocation = parentLocation.replace('setAlert=1', 'setAlert=0');
                                parentLocation = parentLocation.replace('setAlert=2', 'setAlert=0');
                                parentLocation = parentLocation.replace('setAlert=3', 'setAlert=0');
                            }
                            location.href = parentLocation + appendF(window.location.search);
                        }
                    }
                    $("#removeGenreAlertDiv button#btn-no").trigger("click");
                });

            }, 1500);
        });
    });
})(jQuery);
/* below are necessary scripts */
/* global br_productTitle, br_searchTitle */
(function($){
    "use strict";
    $(document).ready(function(){
        var $con, brImgUrl = "/resources/mojito/img/feature/bloomreach_event.png";
		if($.trim(contentPagetype) === "ticket"){
			$con = $("#br_venuecontainer");
		}else if($.trim(contentPagetype) === "event"){
			$con = $("#br_evtcontainer");
			if(StubHub.isStaticOrZoneMap == "false"){
				$con.find(".br-found-heading").css("background-image","url("+ brImgUrl +")");
				$con.find(".br-related-heading").css("background-image","url("+ brImgUrl +")");
			}
		}else if($.trim(contentPagetype) === "intermediateGeo"){
			$con = $("#br_geocontainer");
		}else {
			$con = $("#br_container");
		}
        if(typeof br_productTitle !== "undefined" && br_productTitle && br_productTitle.indexOf("[[") !== 0){
            $con.find(".br-found-heading").text(br_productTitle);
        }
        if(typeof br_searchTitle !== "undefined" && br_searchTitle && br_productTitle.indexOf("[[") !== 0){
            $con.find(".br-related-heading").text(br_searchTitle);
        }
        function getUrlVars(url){
            var vars = {};
            url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
                vars[key] = value;
            });
            return vars;
        }

        function hidePriceQuantity(){
            $con.find(".eventTickets").each(function(i,ele){
                var $ele = $(ele);
                var $a = $ele.find("a").remove();
                $ele.empty().append($a);
            });
        }

        function updateData(eids,callback){
            if(!eids || eids.length === 0){
                callback([]);
            }else{
                var _ids = eids.join(" ");
                var domain, viewingDomain;
                if((location.hostname.match(/srw(e|d|q)\d{1,2}|slc(e|d|q)\d{1,3}|stubhub/)||[])[0]){
                    domain = location.hostname.replace("www.", "publicfeed.");
					viewingDomain = location.hostname.replace("www.", "");
                }else{
                    domain = "publicfeed.stubhub.com";
					viewingDomain = "stubhub.com";
                }
                $.ajax({
                    dataType: "json",
                    url: "//"+domain+"/listingCatalog/select/?q=stubhubDocumentType:event AND id:(" + _ids + ") AND event_date:[NOW TO *] AND allowedViewingDomain:" + viewingDomain + "&wt=json&fl=totalTickets,minPrice,id&json.wrf=?",
                    success: function(data){callback(data.response.docs);},
                    error: hidePriceQuantity
                });
            }
        }

        function updateFields(docs){
            var $p = $con.find("#br-more-products-widget");
            if(docs.length > 0){
                $con.find(".br-sf-widget").hide();
                var show = false;
                for(var i = 0, m = docs.length; i < m; i++){
                    var doc = docs[i],
                        did = doc.id;
                    var $w = $p.find("#br-"+did);
                    $w.show();
                    $w.find("#br-"+did+"-price").text(parseFloat(doc.minPrice).toFixed(2));
                    $w.find("#br-"+did+"-availability").text(doc.totalTickets);
                    show = true;
                }
                if(show){$p.show();}
            }else{
                $p.hide();
            }
        }

        function getProductIds(el){
            var ret = [];
            if(el){
                el = $(el);
                el.find(".eventSell").find("a").each(function(i,elem){
                    var _url = elem.getAttribute("href");
                    var eid = getUrlVars(_url).eventId;
                    if(eid) ret.push(eid);
                });
            }
            return ret;
        }

        $("#br-more-products-table").shTable({
            roundedCorners: (typeof isNewGenrePage !="undefined" && isNewGenrePage) ? false : true,
            useAlternateRowColors: true,
            paginate:false,
            dataTableAoColumns:[
            {"bSortable":false},
            {"bSortable":false},
            {"bSortable":false},
            {"bSortable":false},
            {"bSortable":false}
            ],
            rcThSeparators:[true,true,true,false,false],
            dataTableAaSorting:[[2,"desc"]],
            dataTableAaSortingFixed: [[0, "asc"]]
        });

        updateData(getProductIds("#br-more-products-widget"), updateFields);
    });
})(jQuery);
/** Copyright 2009-2013 StubHub, Inc. All rights reserved. @name live chat @version 1.0 */

var liveChatUtil = {};
;(function ($) {
	var departmentObj = {
		".co.uk":{
			"gen":{ 
				reactive_sign: "58816",
				reactive_non_sign: "58815"
			}
		},
		".com":{
			"gen":{
				reactive_sign: "55869",
				reactive_non_sign: "54522"
			},
			"help":{
				reactive_sign: "57784",
				reactive_non_sign: "54523"
			}
		}
	};
	
	/**
	 * get department object according to the domain
	 */
	var domainName = $.stubhub.domainUtil.getCurrentHostSuffix();
	/**
	 * get department by application
	*/
	var isHelpApp = typeof(helpApp) !== "undefined" ,
		departmentApp = isHelpApp ? "help" : "gen" ;			 
	/**
	 * is a sign in user
	 */
	var isSignIn = isLoggedIn !== "undefined" && isLoggedIn == "true" ;
	/**
	 * get department id according to the different domains, departments and whether user signed in
	 */
	var department = departmentObj[domainName][departmentApp],
		departId =  department ? isSignIn ? department["reactive_sign"] 
										  : department["reactive_non_sign"]
								: '';
	/** 
	 * generate access url by whether user signed in
	 */
	var prop11 = window.s !== "undefined" ? window.s.prop11 : '',
		url = isSignIn ? "https://admin.instantservice.com/Customer?ai=7962&amp;di=" +
							 departId +
							 "&amp;fname=" + fname +
							 "&amp;lname=" + lname +
							 "&amp;email=" + email +
							 "&amp;optionaldata1=" + document.location +
							 "&amp;optionaldata2=" + prop11
					   : "https://admin.instantservice.com/links/7962/" + departId;
	/**
	 * append live chat according to the different department id
	 */
	var onClickFn = "window.open('" + url + "', 'chat_client', 'width=448,height=564,scrollbars=0'); " + "return false;",
		chatButtonImg = '<img alt="Click To Chat" src="/resources/mojito/img/pattern/phoenix/live_chat_button.png" />',
		chatButton = '<a href="" onClick="' + onClickFn + '">' + chatButtonImg + '</a>';
	function agentsAvailable () {
		if(isHelpApp) {
			$(".livechatOff").hide();
			$(".livechatOn").show();
		}
		$('#smartbutton').html(chatButton);
		return true;
	}
	$.extend(liveChatUtil,{
		agentsAvailable: agentsAvailable
	});

	$(function () {
		/* needShowLiveChat{boolean} to identify current page will show live chat.defined
		 * in each page which need to show live chat.
		 * append image to body try to check if cs agent is available
		 */
	    if (typeof(needShowLiveChat) != "undefined" && needShowLiveChat) {
	    	setTimeout(function() {
			$("body").append('<img src="https://rs.instantservice.com/resources/smartbutton' + '/7962/' + departId + '/available.gif?' + Math.floor(Math.random()*10001) + ' "style="width:0;height:0;visibility:hidden;position:absolute;"' + ' onLoad="liveChatUtil.agentsAvailable()" />');
	    	}, 5000);
	    }
	});
	
})(jQuery);